/*
 * @Author: jiutian
 * @Date: 2023-01-31 11:30:00
 * @LastEditTime: 2023-03-21 09:50:58
 * @LastEditors:
 */
const express = require("express");
const app = express();
const chalk = require("chalk");
const requireContext = require("./config/requireContext");
const path = require("path");
const cors = require("cors");
require("./config");
const bodyParser = require("body-parser");
const { ValidationError } = require("express-validation");
const { expressjwt: jwt } = require("express-jwt");
const { server } = require("./project.config");
require("./websoket/index");

// 解析json形式的数据
app.use(bodyParser.json());
// 解析 application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: false }));
app.use(cors());

// 注册全局中间件
app.use((req, res, next) => {
  if (req.query.pageNum) {
    req.query.pageNum = Number(req.query.pageNum);
  }
  if (req.query.pageSize) {
    req.query.pageSize = Number(req.query.pageSize);
  }
  res.cc = (err, code = 403) => {
    res.send({
      code,
      msg: err instanceof Error ? err.message : err,
    });
  };
  next();
});

// 配置需要身份验证的请求
app.use(
  jwt({ secret: server.tokenSecretKey, algorithms: ["HS256"] }).unless({
    path: [/^\/(entry|blogServe)/],
  })
);

//挂载静态资源
app.use("/blogServe", express.static(path.join(__dirname, "/blogServe")));

// 导入路由模块
const routerFileList = requireContext(path.resolve("./router"));
routerFileList.forEach((v) => {
  app.use(`/${v.filename}`, require(`${v.fileUrl}`));
});

app.use((err, req, res, next) => {
  if (err instanceof ValidationError) {
    res.send({
      code: 401,
      msg: "参数校验失败",
      data: err.details,
    });
  } else if (err.name == "UnauthorizedError") {
    res.send({
      code: 402,
      msg: "身份验证失败，请重新登录",
    });
  } else {
    res.send({
      code: 400,
      err,
    });
  }
});

app.listen(process.env.API_PORT, () => {
  console.log(
    chalk.yellow(
      `server running at ${process.env.API_URL}:${process.env.API_PORT}`
    )
  );
});
